﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Portals;
using System.Web;
using Telerik.Web.UI;
using Telerik.Web.UI.Editor.DialogControls;
using System.Linq;
using ToSic.SexyContent.EAV.FieldTemplates;

namespace ToSic.Eav.ManagementUI
{
	public partial class File_EditCustom : FieldTemplateUserControl
	{
		#region Protected Fields/Controls
		protected DotNetNuke.UI.UserControls.LabelControl FieldLabel;
		#endregion

		#region Private Fields
		private ImageManagerDialogConfiguration _imageManagerConfiguration = new ImageManagerDialogConfiguration();
		private FileManagerDialogConfiguration _documentManagerConfiguration = new FileManagerDialogConfiguration();
		private EditorProvider _editorProvider;
		#endregion

		#region Properties
		protected DialogTypeEnum DialogType
		{
			get { return GetMetaDataValue("DialogType", DialogTypeEnum.DocumentManager); }
		}

		protected bool ShowPagePicker
		{
			get { return GetMetaDataValue<bool>("ShowPagePicker") || DialogType == DialogTypeEnum.PagePicker; }
		}

		protected bool ShowImagePicker
		{
			get { return GetMetaDataValue<bool>("ShowImagePicker") || DialogType == DialogTypeEnum.ImageManager; }
		}

		protected bool ShowFilePicker
		{
			get { return GetMetaDataValue<bool>("ShowFilePicker") || DialogType == DialogTypeEnum.DocumentManager; }
		}

		public override object Value
		{
			get { return txtFilePath.Text; }
		}

		public override Control DataControl
		{
			get { return txtFilePath; }
		}
		#endregion

		protected void Page_Load(object sender, EventArgs e)
		{
			DataBind();
		}

		protected override void OnPreRender(EventArgs e)
		{
			if (!IsPostBack)
				txtFilePath.Text = FieldValueEditString;

			InitDialogOpener();

			FieldLabel.Text = GetMetaDataValue("Name", Attribute.StaticName);
			FieldLabel.HelpText = GetMetaDataValue<string>("Notes");

			base.OnPreRender(e);
		}

		#region Dialog Opener

		private void InitEditorProvider()
		{
			_editorProvider = new EditorProvider();

			_editorProvider.Initialize();
			_imageManagerConfiguration = _editorProvider._editor.ImageManager;
			_documentManagerConfiguration = _editorProvider._editor.DocumentManager;
		}

		private void InitDialogOpener()
		{
			InitEditorProvider();

			#region Get View, Update, DeletePaths
			var homeDirectory = PortalSettings.Current.HomeDirectory;
			string[] paths;
			if (MetaData.ContainsKey("Paths") && !String.IsNullOrEmpty(MetaData["Paths"][DimensionIds].ToString()))
				paths = MetaData["Paths"][DimensionIds].ToString().Split(',').Select(p => homeDirectory + p).ToArray();
			else
				paths = _imageManagerConfiguration.ViewPaths;

			#endregion


			if (ShowImagePicker)
			{
				DialogOpener1.DialogDefinitions.Add("ImageManager", GetImageManagerDefinition(paths));
				DialogOpener1.DialogDefinitions.Add("ImageEditor", GetImageEditorDefinition(paths));
			}
			if (ShowFilePicker)
				DialogOpener1.DialogDefinitions.Add("DocumentManager", GetDocumentManagerDefinition(paths));

			DialogOpener1.HandlerUrl = "~/DesktopModules/Admin/RadEditorProvider/DialogHandler.aspx?portalid=" + PortalSettings.Current.PortalId + "&tabid=" + PortalSettings.Current.ActiveTab.TabID;
			DialogOpener1.AdditionalQueryString = "&PreselectedItemUrl=" + HttpUtility.UrlEncode(FieldValueEditString);
			DialogOpener1.EnableEmbeddedSkins = _editorProvider._editor.EnableEmbeddedSkins;
			DialogOpener1.Skin = _editorProvider._editor.Skin;

			InitPickerMenu();
		}

		private void InitPickerMenu()
		{

			var pagePickerMenuItem = blPickerMenu.Items.FindByValue(DialogTypeEnum.PagePicker.ToString());
			if (!ShowPagePicker)
				blPickerMenu.Items.Remove(pagePickerMenuItem);
			else
			{
				pagePickerMenuItem.Attributes.Add("onclick", GetClientOpenDialogCommand(DialogTypeEnum.PagePicker));
			}

			var documentManagerMenuItem = blPickerMenu.Items.FindByValue(DialogTypeEnum.DocumentManager.ToString());
			if (!ShowFilePicker)
				blPickerMenu.Items.Remove(documentManagerMenuItem);
			else
			{
				documentManagerMenuItem.Attributes.Add("onclick", GetClientOpenDialogCommand(DialogTypeEnum.DocumentManager));
			}

			var imageManagerMenuItem = blPickerMenu.Items.FindByValue(DialogTypeEnum.ImageManager.ToString());
			if (!ShowImagePicker)
				blPickerMenu.Items.Remove(imageManagerMenuItem);
			else
			{
				imageManagerMenuItem.Attributes.Add("onclick", GetClientOpenDialogCommand(DialogTypeEnum.ImageManager));
			}
		}

		protected string GetClientOpenDialogCommand()
		{
			return GetClientOpenDialogCommand(DialogType);
		}
		protected string GetClientOpenDialogCommand(DialogTypeEnum dialogType)
		{
			return "ToSexyContent.ItemForm.File.OpenDialog(\"" + DialogOpener1.ClientID + "\", \"" + dialogType + "\", \"" + Attribute.StaticName + "\", " + PortalSettings.Current.PortalId + ");";
		}

		private DialogDefinition GetImageManagerDefinition(string[] paths)
		{
			var imageManagerParameters = new FileManagerDialogParameters
			{
				ViewPaths = paths,
				UploadPaths = paths,
				DeletePaths = paths,
				MaxUploadFileSize = _imageManagerConfiguration.MaxUploadFileSize,
				FileBrowserContentProviderTypeName = _imageManagerConfiguration.ContentProviderTypeName,
				SearchPatterns = _imageManagerConfiguration.SearchPatterns
			};
			imageManagerParameters["IsSkinTouch"] = false;
			if (MetaData.ContainsKey("FileFilter") && !String.IsNullOrEmpty(MetaData["FileFilter"][DimensionIds].ToString()))
				imageManagerParameters.SearchPatterns = MetaData["FileFilter"][DimensionIds].ToString().Split(',');

			var imageManagerDefinition = new DialogDefinition(typeof(ImageManagerDialog), imageManagerParameters)
			{
				ClientCallbackFunction = "ToSexyContent.ItemForm.File.ImageManagerCallback",
				Width = Unit.Pixel(694),
				Height = Unit.Pixel(440)
			};
			imageManagerDefinition.Parameters["Language"] = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
			imageManagerDefinition.Parameters["LocalizationPath"] = "~/DesktopModules/Admin/RadEditorProvider/App_LocalResources/";

			return imageManagerDefinition;
		}

		private DialogDefinition GetDocumentManagerDefinition(string[] paths)
		{
			var documentManagerParameters = new FileManagerDialogParameters
			{
				ViewPaths = paths,
				UploadPaths = paths,
				DeletePaths = paths,
				MaxUploadFileSize = _documentManagerConfiguration.MaxUploadFileSize,
				FileBrowserContentProviderTypeName = _documentManagerConfiguration.ContentProviderTypeName,
				SearchPatterns = _documentManagerConfiguration.SearchPatterns
			};

			documentManagerParameters["IsSkinTouch"] = false;
			if (MetaData.ContainsKey("FileFilter") && !String.IsNullOrEmpty(MetaData["FileFilter"][DimensionIds].ToString()))
				documentManagerParameters.SearchPatterns = MetaData["FileFilter"][DimensionIds].ToString().Split(',');

			var documentManagerDefinition = new DialogDefinition(typeof(DocumentManagerDialog), documentManagerParameters)
			{
				ClientCallbackFunction = "ToSexyContent.ItemForm.File.DocumentManagerCallback",
				Width = Unit.Pixel(694),
				Height = Unit.Pixel(440)
			};
			documentManagerDefinition.Parameters["Language"] = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
			documentManagerDefinition.Parameters["LocalizationPath"] = "~/DesktopModules/Admin/RadEditorProvider/App_LocalResources/";

			return documentManagerDefinition;
		}

		private DialogDefinition GetImageEditorDefinition(string[] paths)
		{
			var imageEditorParameters = new FileManagerDialogParameters
			{
				ViewPaths = paths,
				UploadPaths = paths,
				DeletePaths = paths,
				MaxUploadFileSize = _imageManagerConfiguration.MaxUploadFileSize,
				FileBrowserContentProviderTypeName = _imageManagerConfiguration.ContentProviderTypeName,
				SearchPatterns = _imageManagerConfiguration.SearchPatterns
			};
			imageEditorParameters["IsSkinTouch"] = false;
			if (MetaData.ContainsKey("FileFilter") && !String.IsNullOrEmpty(MetaData["FileFilter"][DimensionIds].ToString()))
				imageEditorParameters.SearchPatterns = MetaData["FileFilter"][DimensionIds].ToString().Split(',');

			var imageEditorDefinition = new DialogDefinition(typeof(ImageEditorDialog), imageEditorParameters)
			{
				Width = Unit.Pixel(832),
				Height = Unit.Pixel(500)
			};
			imageEditorDefinition.Parameters["Language"] = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
			imageEditorDefinition.Parameters["LocalizationPath"] = "~/DesktopModules/Admin/RadEditorProvider/App_LocalResources/";

			return imageEditorDefinition;
		}

		#endregion

		protected enum DialogTypeEnum
		{
			ImageManager,
			DocumentManager,
			PagePicker,
		}
	}
}
